<template>
  <el-col class="app-hv-center app-column app-fill">
    <div class="app-flex-1 app-fill-width pt-8" style="overflow-y: auto">
      <el-form
        ref="form"
        :rules="rules"
        class="app-width-80p app-flex-1"
        :model="form"
        label-width="180px"
      >
        <el-form-item prop="rate" label="*公司名称:">
          <el-input v-model="form.name" />
        </el-form-item>
        <div class="app-flex my-8">
          <div class="required app-h-end" style="line-height: 48px;width: 180px">logo：</div>
          <div class="app-flex-1">
            <el-upload
              action="https://up-z2.qiniup.com"
              :before-upload="getUploadToken"
              :data="qiniuToken"
              accept="image/*"
              :on-success="handleImageSuccess"
              :show-file-list="false"
            >
              <img v-if="form.logo" :src="form.logo" class="app-wh-100px app-circle app-ba-1px-l3">
              <el-button
                v-else
                class="app-ba-1px-l1 app-v-center px-9 py-4 app-round-1 font-weight-bold app-font-18"
                style="background: #FF4DAC; color: #FFF"
              >
                <span style="color: #5D6364" class="mr-2">✚</span>上传logo
              </el-button>
            </el-upload>
          </div>
        </div>
        <el-form-item prop="currentItem" label="*计算方式：">
          <el-select v-model="currentItem" placeholder="请选择计算方式">
            <el-option
              v-for="rateType in rateTypeList"
              :key="rateType.value"
              :label="rateType.label"
              :value="rateType.value"
            />
          </el-select>
        </el-form-item>
        <template v-if="form.floatRate[currentItem-1]">
          <div v-for="item,idx in form.floatRate[currentItem-1].rateDetails" :key="item.currentItem">
            <div class="app-flex">
              <el-form-item :label="`*${rateTypeList[currentItem-1].label}${idx+1}大于:`">
                <el-input v-model="form.floatRate[currentItem-1].rateDetails[idx].value" type="number" />
              </el-form-item>
              <el-form-item :label="`*浮动利率${idx+1}:`">
                <el-input v-model="form.floatRate[currentItem-1].rateDetails[idx].rate" type="number" />
              </el-form-item>

              <i class="el-icon-circle-plus app-font-20 app-pointer mx-5 mt-3" style="color: #409EFF" @click="addRate(idx)" />
              <i v-if="form.floatRate[currentItem-1].rateDetails.length > 1" class="el-icon-remove app-font-20 app-pointer mx-5 mt-3" style="color: #FC4C34" @click="deleteRate(idx)" />
            </div>
          </div>
        </template>
        <el-form-item prop="deliveryPrice" label="是否显示到手价：">
          <el-radio-group v-model="form.deliveryPrice">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="rent" label="是否显示总租金：">
          <el-radio-group v-model="form.rent">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="remainingRent" label="是否显示剩余总租金：">
          <el-radio-group v-model="form.remainingRent">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="deposit" label="是否显示押金：">
          <el-radio-group v-model="form.deposit">
            <el-radio :label="1">开启</el-radio>
            <el-radio :label="0">关闭</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="stages" label="分期显示：">
          <el-checkbox-group v-model="numberPeriods">
            <el-checkbox v-for="stage in stages" :key="stage" :label="stage">{{ stage + '期' }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <template v-if="form.params && form.params.length > 0">
          <div v-for="item,idx in form.params" :key="idx" class="app-flex">
            <el-form-item prop="rate" :label="`*加价${idx+1}起点金额大于:`">
              <el-input v-model="form.params[idx].startingPoint" type="number" />
            </el-form-item>
            <el-form-item prop="params" :label="`*设备加价${idx+1}:`">
              <el-input v-model="form.params[idx].premium" type="number" />
            </el-form-item>
            <i class="el-icon-circle-plus app-font-20 app-pointer mx-5 mt-3" style="color: #409EFF" @click="addParam(idx)" />
            <i v-if="form.params.length > 1" class="el-icon-remove app-font-20 app-pointer mx-5 mt-3" style="color: #FC4C34" @click="deleteParam(idx)" />
          </div>
        </template>
      </el-form>
    </div>
    <div class="app-hv-center">
      <el-button class="app-fill-width my-6" type="warning" @click="save"> 确认保存 </el-button>
      <el-button class="app-fill-width my-6" type="warning" @click="viewQrcode"> 查看二维码 </el-button>
    </div>
    <el-dialog
      :visible.sync="show"
      width="400px"
    >
      <div class="app-white pa-2 app-hv-center">
        <vue-qr :text="qrText" :size="300" />
      </div>
    </el-dialog>
  </el-col>
</template>

<script>
import {
  getQiniuToken,
  getFloatSettings,
  updateFloatSettings
} from '@/api/user'
import vueQr from 'vue-qr'
export default {
  components: { vueQr },
  data: () => ({
    show: false,
    rules: {
      endTime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }]
    },
    userInfo: JSON.parse(localStorage.getItem('userInfo')),
    stages: [2,3,4,5,6,7,8,9,10,11,12],
    form: {
      logo: '',
      name: '个人音乐后台管理',
      rate: null,
      deliveryPrice: 0,
      rent: 0,
      deposit: 0,
      floatRate: [],
      params: [],
      remainingRent: 0
    },
    // 选中的计算方式
    currentItem: 1,

    rateTypeList: [{
      label: '设备金额',
      value: 1
    },{
      label: '期数',
      value: 2
    },{
      label: '首期租金',
      value: 3
    },{
      label: '欠款额',
      value: 4
    }],
    numberPeriods: [],
    qrText: '',
    qiniuToken: {}
  }),
  watch: {
    // 切换方式遍历每个修改状态
    currentItem(val) {
      this.form.floatRate.forEach((item,index) => {
        index === val - 1 ? item.isThis = 1 : item.isThis = 0
      })
    }
  },
  mounted() {
    this.getData()
    this.qrText = `${location.href.split('#')[0]}#/rent-calculate-float?userId=${this.userInfo.userId}`
    console.log(this.qrText)
  },
  methods: {
    getUploadToken() {
      return getQiniuToken().then((res) => {
        this.qiniuToken = res.data
      })
    },
    handleImageSuccess(res, file) {
      this.form.logo = this.qiniuToken.host + '/' + res.key
    },
    getData() {
      // 获取初始化数据
      getFloatSettings().then(res => {
        if (res.code === 200) {
          this.form = res.data
          if (!this.form.params) {
            this.form.params = Array.from({ length: 1 }, (v, i) => {
              return {
                premium: null,
                startingPoint: null
              }
            })
          }
          if (!this.form.floatRate) {
            // 初始化
            this.form.floatRate = Array.from({ length: 4 }, (v, i) => {
              return {
                currentItem: i + 1,
                isThis: i === 0 ? 1 : 0,
                rateDetails: [
                  {
                    value: 0,
                    rate: 0
                  }
                ]
              }
            })
          } else {
            // 查询当前选中项的下标并赋值
            this.currentItem = this.form.floatRate.findIndex(item => item.isThis === 1) + 1
          }
          this.numberPeriods = this.form.numberPeriods
        }
      })
    },
    // 保存配置
    save() {
      this.form.numberPeriods = this.numberPeriods
      updateFloatSettings(this.form).then((res) => {
        if (res.code === 200) {
          this.getData()
          this.$message({ type: 'success', message: '操作成功' })
        }
      })
    },
    addRate(idx) {
      this.form.floatRate[this.currentItem - 1].rateDetails.splice(idx + 1,0,{
        value: 0,
        rate: 0
      })
    },
    deleteRate(idx) {
      this.form.floatRate[this.currentItem - 1].rateDetails.splice(idx,1)
    },
    addParam(idx) {
      this.form.params.splice(idx + 1,0,{
        premium: null,
        startingPoint: null
      })
    },
    deleteParam(idx) {
      this.form.params.splice(idx,1)
    },
    viewQrcode() {
      this.show = true
    }
  }
}
</script>
